package com.txhy.certificatechain.utils;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.txhy.certificatechain.R;
import com.txhy.certificatechain.model.bean.MailListBean;
import com.txhy.certificatechain.ui.activity.share.ShareActivity;
import com.txhy.certificatechain.ui.activity.user.LoginActivity;
import com.txhy.certificatechain.ui.widget.IOSDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2018-2030, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: CommUtils.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述:
 * 创建时间: 2018/9/19 17:22
 * 更新时间：2018/9/19 17:22
 * -----------------------------------------------------------------
 * 2018/9/19 17:22: 创建 CommUtils.java (侯建军);
 * -----------------------------------------------------------------
 */
public class CommUtils {
    //获取IMEI码
    @SuppressLint({"HardwareIds", "MissingPermission"})
    public static String getIMEI(Context context) {
        String imei;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (Exception e) {
            imei = "";
        }
        return imei;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }


    public static void showHomePopup(final Context context, View viewPop) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_homepopup, null);
        view.setBackgroundColor(Color.WHITE);//给view视图设置背景颜色（灰色），不然看不到效果
        //实例化控件
        LinearLayout ll_msg = view.findViewById(R.id.ll_msg);
        LinearLayout ll_addFri = view.findViewById(R.id.ll_addFri);
        LinearLayout ll_shared = view.findViewById(R.id.ll_shared);
        //实例化PopupWindow
        final PopupWindow window = new PopupWindow(view, 600, ViewGroup.MarginLayoutParams.WRAP_CONTENT);//设置PopupWindow的显示大小
        window.setFocusable(true);//设置popupwindow可以获取焦点
        //给pupupwindow设置一个背景 透明的,以便点击popupwindow外边时候可以实现消失
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setOutsideTouchable(true);//设置点击外部消失
        window.showAsDropDown(viewPop, -500, 0);//显示在按钮下方
        ll_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, ShareActivity.class));
            }
        });
        ll_addFri.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PrefUtil.getLoginBoolean(context)) {
                    CommUtils.doToLoad(context);
                    return;
                }
            }
        });
        ll_shared.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, ShareActivity.class));
            }
        });
    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(),
                "desheng");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            ToastUtil.showLong(context, "保存失败");
            e.printStackTrace();
        } catch (IOException e) {
            ToastUtil.showLong(context, "保存失败");
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
            ToastUtil.showLong(context, "保存成功");
        } catch (FileNotFoundException e) {
            ToastUtil.showLong(context, "保存失败");
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(file.getPath()))));
    }

    public static String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }

    public static void sortList(List<MailListBean.DataEntity> list) {
        transferList(list);
    }

    /**
     * 进行冒泡排序
     *
     * @param list
     */
    private static void transferList(List<MailListBean.DataEntity> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size() - 1 - i; j++) {
                exchangeNameOrder(j, list);
            }
        }
    }

    /**
     * 交换两个名字的顺序,根据首字母判断
     *
     * @param j
     * @param list
     */
    private static void exchangeNameOrder(int j, List<MailListBean.DataEntity> list) {
        String namePinYin1 = list.get(j).getNamePinYin();
        String namePinYin2 = list.get(j + 1).getNamePinYin();

        int size = namePinYin1.length() >= namePinYin2.length() ? namePinYin2.length() : namePinYin1.length();
        for (int i = 0; i < size; i++) {
            char jc = namePinYin1.charAt(i);
            char jcNext = namePinYin2.charAt(i);
            if (jc < jcNext) {//A在B之前就不用比较了
                break;
            }
            if (jc > jcNext) {//A在B之后就直接交换,让A在前面B在后面
                MailListBean.DataEntity nameBean = list.get(j);
                list.set(j, list.get(j + 1));
                list.set(j + 1, nameBean);
                break;
            }
            //如果AB一样就继续比较后面的字母
        }
    }

    public static void doToLoad(final Context context) {
        new IOSDialog(context).radius(10)
                .leftText("取消")
                .contentText("点击去登录")
                .titleText("您还没有登录")
                .rightText("登录")
                .setIOSDialogListener(new IOSDialog.IOSDialogListener() {
                    @Override
                    public void Left(Dialog dialog) {
                        dialog.dismiss();
                    }

                    @SuppressLint("MissingPermission")
                    @Override
                    public void Right(Dialog dialog) {
                        context.startActivity(new Intent(context, LoginActivity.class));
                        dialog.dismiss();
                    }
                })
                .layout()
                .show();
    }

    public static void callPhone(final String phoneNum, final Context context) {
        new IOSDialog(context).radius(10)
                .leftText("取消")
                .contentText("拨打电话")
                .titleText(phoneNum)
                .rightText("呼叫")
                .setIOSDialogListener(new IOSDialog.IOSDialogListener() {
                    @Override
                    public void Left(Dialog dialog) {
                        dialog.dismiss();
                    }

                    @SuppressLint("MissingPermission")
                    @Override
                    public void Right(Dialog dialog) {
                        Intent intent = new Intent(Intent.ACTION_CALL);
                        Uri data = Uri.parse("tel:" + phoneNum);
                        intent.setData(data);
                        context.startActivity(intent);
                        dialog.dismiss();
                    }
                })
                .layout()
                .show();
    }

    //复制内容
    public static void copyText(String text, Context context) {
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(text.trim()); //将内容放入粘贴管理器,在别的地方长按选择"粘贴"即可
        ToastUtil.showLong(context, "复制成功");
    }

    private static TimePickerView pvTime;

    public static void showTimePicker(Context context,final TextView tv_time) {
        pvTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tv_time.setText(CommUtils.getTime(date));
            }
        })
                .setType(new boolean[]{true, true, false, false, false, false})
                .isDialog(true)
                .setSubmitColor(UIUtils.getColor(R.color.ed584c))//确定按钮文字颜色
                .setCancelColor(UIUtils.getColor(R.color.text666))//取消按钮文字颜色
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
        pvTime.show();

    }

    public static void showTimePickerYearMonthDay(Context context, final TextView tv_time) {
        pvTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tv_time.setText(CommUtils.getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true)
                .setSubmitColor(UIUtils.getColor(R.color.ed584c))//确定按钮文字颜色
                .setCancelColor(UIUtils.getColor(R.color.text666))//取消按钮文字颜色
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
        pvTime.show();
    }

    /*
     * 毫秒转化
     */
    public static String formatTime(long ms) {

        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;

        String strDay = day < 10 ? "0" + day : "" + day; //天

        return (Integer.parseInt(strDay) + 1) + "";
    }


    public static BigDecimal calServiceFee(BigDecimal amount, Double rateNum) {

        BigDecimal rate = BigDecimal.valueOf(rateNum);
        BigDecimal serviceFee = rate.multiply(amount.setScale(0, BigDecimal.ROUND_UP));
        return serviceFee;
    }


    public static String getDataTime(String time) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'ToastUtil'hh:mm:ss.SSSZ");
        Date result;
        result = df.parse(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(result);
    }

    public static String getDataTimehms(String time) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'ToastUtil'hh:mm:ss.SSSZ");
        Date result;
        result = df.parse(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(result);
    }

    public static String timeToSS(String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        long millionSeconds = sdf.parse(time).getTime();//毫秒
        return millionSeconds + "";
    }
}